package com.open.pokergames.main

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.jiangyy.easydialog.CommonDialog
import com.king.app.dialog.AppDialog
import com.king.app.dialog.AppDialogConfig
import com.king.app.updater.AppUpdater
import com.open.pokergames.NetConfig
import com.open.pokergames.R
import com.open.pokergames.base.fragment.EventBusBaseFragment
import com.open.pokergames.biz.views.admin.RoomCardLogActivity
import com.open.pokergames.comm.repository.cache.LocalCache
import com.open.pokergames.comm.repository.entity.AppVersionEntity
import com.open.pokergames.comm.repository.entity.ResultInfo
import com.open.pokergames.comm.repository.viewModel.SystemViewModel
import com.open.pokergames.comm.user.UserEditActivity
import com.open.pokergames.comm.userCenter.WelcomeActivity
import com.sinothk.android.utils.XUtils
import kotlinx.android.synthetic.main.mine_fragment_main.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class MineMainFragment : EventBusBaseFragment(), View.OnClickListener {

    private var viewModel: SystemViewModel? = null

    private var currView: View? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (currView == null) {
            currView = inflater.inflate(R.layout.mine_fragment_main, container, false)
        }
        return currView
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = SystemViewModel()

        initView()
        setListener()
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        val loginUser = LocalCache.getUser()
        userNameTv.text = XUtils.string().getNotNullValue(loginUser.userName, "未登录")
        userAccTv.text = "ID: " + XUtils.string().getNotNullValue(loginUser.account, "无")

        Glide.with(requireContext()).load(NetConfig.getImageUrl(loginUser.userAvatar))
            .placeholder(R.drawable.default_img)
            .error(R.drawable.default_img)
            .into(imageView)

        val version = "V${XUtils.app().appVersionName}/${XUtils.app().appVersionCode}"
        versionTv.text = version

        showOpt(loginUser.roles)
    }

    private fun showOpt(roles: String?) {
        if (roles != null && roles.contains("admin1")) {
            roomCardItem.visibility = View.VISIBLE
        } else {
            roomCardItem.visibility = View.GONE
        }
    }

    private fun setListener() {
        roomCardItem.setOnClickListener(this)
        appUpdateItem.setOnClickListener(this)

        settingBtn.setOnClickListener(this)
        exitBtn.setOnClickListener(this)

        imageView.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            appUpdateItem -> {
                showLoadingDialog("正在检测")
                viewModel?.lastVersion("MINE")
                return
            }
//            exitItem -> {
//                LocalCache.logout()
//                updateView()
//                XUtils.toast().show("已进入游客环境")
////                XUtils.page().finishAll()
////                // 登录检测
////                XUtils.intent().openActivity(activity, LoginActivity::class.java)
////                    .startInFragment(this)
//                return
//            }

            imageView -> {
                XUtils.intent().openActivity(activity, UserEditActivity::class.java)
                    .requestCode(600)
                    .startInFragment(this)
            }
            roomCardItem -> {
                XUtils.intent().openActivity(activity, RoomCardLogActivity::class.java)
                    .requestCode(500)
                    .startInFragment(this)
            }

//            settingBtn -> {
//                XUtils.intent().openActivity(activity, SettingActivity::class.java)
//                    .startInFragment(this)
//            }
            exitBtn -> {
                CommonDialog.Builder(activity)
                    .setCancelable(false)
                    .setTitle("退出提示")
                    .setMessage("确定退出游戏吗？")
                    .setPositiveButton("退出") {
                        LocalCache.logout()
                        XUtils.page().finishAll()
                        XUtils.intent().openActivity(activity, WelcomeActivity::class.java)
                            .startInFragment(this)
                    }.setNegativeButton("取消") {
                    }.show()
            }
        }
    }

    //
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<String>) {

        if ("getMineViewData" != result.eventType) {
            return
        }

//        refreshLayout.refreshComplete()
//
//        when (result.code) {
//            ResultInfo.SUCCESS -> {
//                showCountView(result.data)
//            }
//            ResultInfo.TOKEN_OVERDUE -> {
//            }
//            else -> {
//            }
//        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 600) {
            initView()
        }
    }

    //
//    private fun showCountView(data: MineCountBean?) {
//        if (data == null) {
//            myTaskTv.text = "0"
//            myExamCountTv.text = "0"
//            myNoticeTv.text = "0"
////            myJiFenTv.text = "0"
//        } else {
//            myTaskTv.text = data.taskCount.toString()
//            myExamCountTv.text = data.examCount.toString()
//            myNoticeTv.text = data.noticeCount.toString()
////            myJiFenTv.text = data.gralCount.toString()
//        }
//    }
//
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveAppVersionEventBus(resultInfo: ResultInfo<AppVersionEntity?>) {

        if ("MINE" != resultInfo.eventType) {
            return
        }

        hideLoadingDialog()

        if (resultInfo.code == ResultInfo.SUCCESS) {
            val appVersion = resultInfo.data
            if (appVersion != null) {
                if (appVersion.verCode > XUtils.app().appVersionCode) { //简单弹框升级
                    val config = AppDialogConfig()
                    config.setTitle("新版本升级")
                        .setOk("升级")
                        .setContent(
                            XUtils.string().getNotNullValue(appVersion.updateContent)
                        ).onClickOk = View.OnClickListener { _: View? ->
                        if (XUtils.string().isNotEmpty(appVersion.diskPath)) {
                            AppUpdater.Builder()
                                .serUrl(NetConfig.getAppUrl(appVersion.diskPath))
                                .build(requireActivity())
                                .start()
                            XUtils.toast().show("正在通知栏中下载...")
                        } else {
                            XUtils.toast().show("地址不可用")
                        }
                        AppDialog.INSTANCE.dismissDialog()
                    }
                    AppDialog.INSTANCE.showDialog(requireActivity(), config)
                } else {
                    XUtils.toast().show("当前已是最新版本")
                }
            }
        } else if (resultInfo.code == ResultInfo.TOKEN_OVERDUE) {
        } else {
            XUtils.toast().show(resultInfo.msg)
        }
    }

}